//
//  LeveragedTradeViewModel.swift
//  Exchange
//
//  Created by rui on 2018/7/4.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class LeveragedTradeViewModel: KlineViewModel {
    @objc dynamic var refreshBool:Bool = false
    
    var depthServer = ServerDepth()
    var buyPrice:Double = 0.00
    var sellPrice:Double = 0.00
    
    var regularModel:CoinRegularModel =  CoinRegularModel() //币种对应的规则
    
    ///币种数组
    lazy var coninKidArray:Array<TradeCoinModel> = {
        let array:Array<TradeCoinModel> = []
        return array
    }()
    
//    var selectStates:Bool = false //标记买入 false 或 卖出 true
    
    var curretSelectModel = LeverDataModel()
    
    var isMarketBool:Bool = false
  
    
    //资产数组
    lazy var dateArr:Array<AssetModel> = {
        let array:Array<AssetModel> = []
        return array
    }()
    
    lazy var request: LeverRequest = {
        let api = LeverRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var assetRequest: AssetRequest = {
        let api = AssetRequest()
        api.type = .leverType
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var orderRequest:LeverOrderRequest = {
        let api = LeverOrderRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    override func loadData() {
        super.loadData()
//        depthServer.symbol = symbolName
//        SocketManager.shared.subscribe(server: depthServer)
    }
    
    override func clean() {
        super.clean()
//        SocketManager.shared.cancelSubscribe(server: depthServer)
    }
    
    
    /// 修改深度状态
    ///
    /// - Parameter states: true 订阅 false 取消
    func changeDepthStates(states:Bool) {
        buyPrice = 0.00
        sellPrice = 0.00
        self.delegate?.socketDepthDataChange?(askPrice: buyPrice, bidPrice: sellPrice)
        let symbols = coinModel.name.replacingOccurrences(of: "/", with: "_")
        if symbols.count == 0 {
            return
        }
        let nameArr = symbols.components(separatedBy: "_")
        if nameArr.count < 2 {
            return
        }
        if nameArr.last == nil {
            return
        }
        
        var tickServer = ServerDepth()
        tickServer.symbol = symbols
        if states == true {
            SocketManager.shared.subscribe(server: tickServer)
        }else {
            SocketManager.shared.cancelSubscribe(server: tickServer)
        }
    }
    
    /// 订阅推送
    ///
    /// - Parameter states: 订阅 or 取消
    func changePairStates(states:Bool)  {
        let symbols = coinModel.name
        if symbols.count == 0 {
            return
        }
        let nameArr = symbols.components(separatedBy: "/")
        if nameArr.count < 2 {
            return
        }
        if nameArr.last == nil {
            return
        }
        if states == true {
            APPTransactionPair.default.subscribe(key: nameArr.last!)
        }else {
            APPTransactionPair.default.cancelSubscribe(key: nameArr.last!)
        }
        
    }
    
    /// 获取不同币种对应的信息
    ///
    /// - Parameter coinName: 币种名称 默认BTC CNY
    func archiveCoinInformation(block:securityBlock? = nil)  {
        AppContext.default.getTradeCoins { (array) in
            self.coninKidArray = array
            if block != nil {
                block!()
            }
        }
    }
    
    
    /// 获取币种规则
    func archiveCoinRegular() {
        self.regularModel = CoinRegularModel()
        self.request(request: request, success: {[weak self] (result) in
            if result == nil {
                return
            }
            guard let dic = result!["data"] as? [String:Any]? else {
                return
            }
            
            self?.regularModel = CoinRegularModel(JSON: dic!)!
            
            
        }) { (response) in
            
        }
        
    }
    
    /// 获取杠杆资产
    ///
    /// - Parameter
    func archiveInformation()  {
        CYMBShow.openIndicator(message: nil, view: nil)
        self.request(request: assetRequest, success: {[weak self] (result) in
            CYMBShow.colseIndicator(view: nil)
            let dic:[String:Any]? = result != nil ? result : nil
            if dic == nil {
                return
            }
            if dic?["data"] as? Array<[String : Any]> == nil  {
                return
            }
            
            let array:Array<[String : Any]> = dic?["data"] as! Array<[String : Any]>
            for dic in array {
                let model = AssetModel(JSON: dic)
                if model != nil {
                    self?.dateArr.append(model!)
                }
            }
//            self?.coinNumber()
        }) {(response) in
            CYMBShow.colseIndicator(view:nil)
        }
    }
    
    func socket(didReadDepth data: [String : Any]) {
        var askPirce:Double = 0
        var bidPrice:Double = 0
        if let symbol = data["symbol"] as? String, symbolName != symbol {
            self.delegate?.socketDepthDataChange?(askPrice: askPirce, bidPrice: bidPrice)
            return
        }
        guard var newData = data["data"] as? [String:Any]  else {
            self.delegate?.socketDepthDataChange?(askPrice: askPirce, bidPrice: bidPrice)
            return
        }
        newData.removeValue(forKey: "tick")
        if let mydata = newData["a"] as? [[Double]]{
            if let last = mydata.last, let ask = last.first {
                askPirce = ask
                buyPrice = askPirce
            }
            
        }
       
        ///取出卖出价的最低的价格
        if let mydata = newData["b"] as? [[Double]]{
            if let first = mydata.first, let bid = first.first {
                bidPrice = bid
                sellPrice = bid
            }
        }
        self.delegate?.socketDepthDataChange?(askPrice: askPirce, bidPrice: bidPrice)
    }
    
    override func socket(didReadTick data: [String:Any]) {
        APPTransactionPair.default.updateParameters(data:data)
        self.refreshBool = true
        super.socket(didReadTick: data)
    }
}

extension LeveragedTradeViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        let block = self.successBlockDic.object(forKey: request.path())
        if ((block as? success) != nil) {
            (block as! success)(data)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        let block = self.failBlockDic.object(forKey: request.path())
        if ((block as? fail) != nil) {
            (block as! fail)(request)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? LeverRequest {
        pramas.updateValue(coinModel.name.count != 0 ? coinModel.name : "", forKey: "coinCode")
        }else if let _ = request as? LeverOrderRequest {
            pramas.updateValue(curretSelectModel.isBuyBool ? 0 : 1, forKey: "position")
            let arr =  coinModel.name.components(separatedBy: "/")
            if arr.count > 1 {
                pramas.updateValue(arr.last!, forKey: "sourceCoin")
                pramas.updateValue(arr.first!, forKey: "targetCoin")
            }
            pramas.updateValue(curretSelectModel.number, forKey: "tradeAmount")
            if !self.isMarketBool {
                pramas.updateValue(curretSelectModel.price, forKey: "tradePrice")
            }
            pramas.updateValue(isMarketBool ? 0 : 1, forKey: "tradeType")
            pramas.updateValue("123456", forKey: "tradePwd")
            if AppInfo.default.userId != nil {
                pramas.updateValue(AppInfo.default.userId!, forKey: "userId")
            }
            pramas.updateValue(curretSelectModel.lossScales, forKey: "stopLoss")
            pramas.updateValue(curretSelectModel.profitScales, forKey: "stopProfit")
            pramas.updateValue(curretSelectModel.bail[curretSelectModel.selectIndex], forKey: "leverage")
        }
        return pramas
    }
}


// MARK: - 限价 市价购买操作
extension LeveragedTradeViewModel {
    
    
    ///下订单
    func transOrder()  {
        
        self.orderRequest.isMarketBool = self.isMarketBool
        self.request(request: self.orderRequest, success: {[weak self] (result) in
            CYMBShow.showMessage("杠杆下单成功")
            self?.archiveInformation()
            SelectActionManger.manager.close()
            
        }) { (response) in
            if response.errorMsg.count != 0 {
            CYMBShow.showMessage(response.errorMsg)
            }
        }
        
    }
    
    
    
}
